package com.yyplatform.admin.platform.file.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.exception.ServiceException;
import com.yyplatform.admin.platform.file.model.dto.SysFileConfigDTO;
import com.yyplatform.admin.platform.file.model.dto.SysFileConfigLocalFormDTO;
import com.yyplatform.admin.platform.file.model.entity.SysFileEntity;
import com.yyplatform.admin.platform.file.model.enums.FileStorageTypeEnum;
import com.yyplatform.admin.platform.file.repository.SysFileRepository;
import com.yyplatform.admin.platform.file.service.FileConfigService;
import com.yyplatform.admin.platform.file.service.SysFileUploadService;
import com.yyplatform.admin.platform.file.utils.FileUrlUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-24
 */
@Service
@Slf4j
public class SysFileUploadServiceImpl implements SysFileUploadService {
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    @Autowired
    private SysFileRepository sysFileRepository;
    @Autowired
    private FileConfigService fileConfigService;

    @Override
    public String uploadFile(MultipartFile uploadFile) {


        SysFileConfigDTO fileConfigDTO = fileConfigService.getConfig();

        if (fileConfigDTO == null) {
            log.error("文件配置为空");
            throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
        }


        if (StringUtils.equals(fileConfigDTO.getStorageType(), FileStorageTypeEnum.LOCAL.getValue())) {
            return uploadFile(uploadFile, fileConfigDTO.getLocalFormDTO());
        }


        throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
    }


    private String uploadFile(MultipartFile uploadFile, SysFileConfigLocalFormDTO localFormDTO) {
        log.info("begin to upload file, localFormDTO: {}, file:{} ", localFormDTO, uploadFile);

        try {
            String format = sdf.format(new Date());
            File folder = new File(FileUrlUtils.addLastSlash(localFormDTO.getRootPath()) + format);
            if (!folder.isDirectory()) {
                boolean bb = folder.mkdirs();
                if (!bb) {
                    log.error("创建文件夹失败");
                    throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
                }
            }


            // 对上传的文件重命名，避免文件重名
            String oldName = uploadFile.getOriginalFilename();
            String newName = UUID.randomUUID()
                    + oldName.substring(oldName.lastIndexOf("."), oldName.length());


            // 文件保存
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            String filePath =
                    FileUrlUtils.addLastSlash(localFormDTO.getDomain()) // http://localhost:8080/
                            + FileUrlUtils.delFirstAddLastSlash(localFormDTO.getUrlPrefix())   // files/
                            + FileUrlUtils.addLastSlash(format) // 2025/04/16/
                            + newName;  //  123123123123123123123.jpg

            //
            SysFileEntity sysFileEntity = new SysFileEntity();
            sysFileEntity.setUrl(filePath);
            sysFileEntity.setOriginalFilename(uploadFile.getOriginalFilename());
            sysFileEntity.setFileSize(uploadFile.getSize());
            sysFileEntity.setContentType(uploadFile.getContentType());


            sysFileRepository.save(sysFileEntity);

            return filePath;
        } catch (Exception e) {
            log.error("上传文件异常", e);
            throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
        }
    }


}
